package com.nowcoder.community.controller;

import com.google.code.kaptcha.Producer;
import com.nowcoder.community.dao.LoginTicketMapper;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.XaCommunityConstant;
import com.nowcoder.community.util.XaCommunityUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.mail.Multipart;
import javax.servlet.http.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Controller
public class LoginController implements XaCommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Resource
    private UserService userService;
    @Resource
    private Producer kaptchaProducer;
    @Resource
    private UserMapper userMapper;
    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;
    @Resource
    private LoginTicketMapper loginTicketMapper;
    @Resource
    private HostHolder hostHolder;
    @GetMapping("/register")//跳转前端注册页面
    public String getRegisterPage() {
        return "/site/register";
    }
    @GetMapping("/login")//跳转前端登录页面
    public String getLoginPage() {
        return "/site/login";
    }
    @GetMapping("/letter")//跳转前端短信页面
    public String getLetterPage(){
        return "site/letter";
    }
    @GetMapping("/forget")//跳转前端忘记密码页面
    public String getForgetPage(){
        return "/site/forget";
    }
    @GetMapping("/setting")//跳转前端个人设置页面
    public String getSettingPage(){
        return "/site/setting";
    }
    @RequestMapping(path = "/register",method = RequestMethod.POST)
    public String register(Model model, User user) {
        //方法调用前，springmvc会自动实例化Model和User，同时把User注入到Model
        Map<String, Object> map = userService.register(user);
        if(map.isEmpty()) {
            model.addAttribute("msg","您已成功注册，请尽快去邮箱进行激活");
            model.addAttribute("target","/index");
            return "/site/operate-result";
        }else {
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "/site/register";
        }
    }
    @GetMapping("/activation/{userId}/{code}")//激活账号
    public String activation(Model model, @PathVariable("userId") int userId,
                             @PathVariable("code")String code ){
        int result = userService.activation(userId, code);
        if(result==ACTIVATION_SUCCESS){
            model.addAttribute("mgs","激活成功，您的账号已经可以正常使用了！");
            model.addAttribute("target","/login");
        }
        else if(result==ACTIVATION_REPEAT){
            model.addAttribute("mgs","无效激活，您的账号已经激活了！");
            model.addAttribute("target","/index");
        }
        else if(result==ACTIVATION_FAILURE){
            model.addAttribute("mgs","激活失败，您提供的激活码不正确！");
            model.addAttribute("target","/index");
        }
        return "/site/operate-result";
    }
    @GetMapping("/kaptcha")//获取激活码
    public void getKaptcha(HttpServletResponse response, HttpSession session){
        //1.生成验证码
        String text=kaptchaProducer.createText();
        //1.1通过生成的验证码文本生成验证码图片
        BufferedImage image = kaptchaProducer.createImage(text);

        //2.验证码存入Session
        session.setAttribute("kaptcha",text);

        //3.将验证码发送给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os=response.getOutputStream();
            ImageIO.write(image,"png",os);
        } catch (IOException e) {
            logger.error("响应验证码失败："+e.getMessage());
        }
    }
    @PostMapping("/login")//发起登录请求
    public String login(String username,String password,
                        String code,boolean rememberme,
                        Model model,HttpSession session,
                        HttpServletResponse response){
        String kaptcha =(String)session.getAttribute("kaptcha");

        //如果验证码和参数码有一不存在或者不相同直接返回错误
        if (StringUtils.isBlank(kaptcha)||StringUtils.isBlank(code)||!code.equalsIgnoreCase(kaptcha)) {
            model.addAttribute("codeMsg","验证码错误");
            return "/site/login";
        }

        //检查账号密码
        int expireSeconds=rememberme?REMEMBER_EXPIRED_SECONDS :DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expireSeconds);

        //如果map不存在ticket
        if(!map.containsKey("ticket")){
            //给模型添加用户名和密码
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            //返回到登录页面
            return "/site/login";
        }

        //如果map存在ticket
        //获取ticket
        String ticket=(String) map.get("ticket");
        //存入cookie
        Cookie cookie=new Cookie("ticket",ticket);
        //setcookie的路径和最大年龄
        cookie.setPath(contextPath);
        cookie.setMaxAge(expireSeconds);
        //给response添加cookie
        response.addCookie(cookie);
        return "redirect:/index";
    }
    @GetMapping("/logout")//注销登录
    public String logout(@CookieValue("ticket")String ticket){
        userService.logout(ticket);
        return "redirect:/login";
    }
    @PostMapping("/forget")//发起忘记密码请求
    public String forget(HttpSession session,Model model,
                        String email, String verifycode,String password){
        //1.如果页面码为空，返回"/site/forget"，添加前端信息

        if (verifycode==null) {
            model.addAttribute("codeMsg","验证码不能为空");
            return "/site/forget";
        }

        //2.如果页面码不等于session验证码，返回"/site/forget"，添加前端信息
        String sessionCode=(String) session.getAttribute("code");
        if(!verifycode.trim().equalsIgnoreCase(sessionCode.trim())){
            model.addAttribute("codeMsg","验证码错误");
            return "/site/forget";
        }

        //3.如果session验证码有效期过期，返回"/site/forget"，添加前端信息
        if(LocalDateTime.now().isAfter((LocalDateTime) session.getAttribute("expirationTime"))){
            model.addAttribute("codeMsg","验证码已过期，请重新获取验证码");
            return "/site/forget";
        }

        //4.调用service层的forget方法
        Map<String, Object> map=userService.forget(email,verifycode,password);

        //4.1如果获取的map信息集合为空即修改密码成功
        //   在业务层forget中只有密码错误，结果集才有添加密码错误的信息
        if (map==null||map.isEmpty()) {
             model.addAttribute("msg","密码修改成功");
             model.addAttribute("target","/login");
             //4.2返回"/site/operate-result"
             return "/site/operate-result";
        }

        //5.如果获取的map信息集合不为0，修改不成功，添加密码信息给前端，并重新回到前端forget
        model.addAttribute("passwordMsg",map.get("passwordMsg"));
        model.addAttribute("codeMsg",map.get("codeMsg"));
        model.addAttribute("emailMsg",map.get("emailMsg"));

        //6.返回给前端页面视图
        return "/site/forget";
    }
    @GetMapping("/getCode")//忘记密码---发送邮箱验证码
    public String getCode(String email,Model model,HttpSession session) {
        //1.调用业务层获取结果集----给指定email用户发送邮箱来获取验证码
        Map<String, Object> map = userService.getCode(email);
        
        if (map.containsKey("emailMsg")) {//有错误的情况下
            model.addAttribute("emailMsg", map.get("emailMsg"));
        } else {//正确的情况下，向邮箱发送了验证码
            model.addAttribute("msg", "验证码已经发送到您的邮箱，5分钟内有效！");
            //将验证码存放在 session 中，后序和用户输入的信息进行比较
            session.setAttribute("code",map.get("code"));
            //后序判断用户输入验证码的时候验证码是否已经过期
            session.setAttribute("expirationTime",map.get("expirationTime"));
        }
        return "/site/forget";
    }
}